﻿using System;
using System.IO;
using System.Web.Mvc;

namespace SellAndBuy.Web.Controllers.ActionResults
{
    public class ImageActionResult : ActionResult
    {
        public byte[] Image { get; set; }
        public string FileName { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (Image == null)
                throw new ArgumentNullException("Image");

            if (string.IsNullOrWhiteSpace(FileName))
                throw new ArgumentNullException("FileName");

            context.HttpContext.Response.Clear();

            var imageFormat = GetContentType(FileName);
            context.HttpContext.Response.ContentType = imageFormat;

            using (var ms = new MemoryStream(Image))
            {
                ms.WriteTo(context.HttpContext.Response.OutputStream);
            }
            context.HttpContext.Response.End();
        }

        protected string GetContentType(string name)
        {
            const string defaultType = "image/gif";
            if (string.IsNullOrWhiteSpace(name) || !Path.HasExtension(name))
            {
                return defaultType;
            }
            var ext = Path.GetExtension(name);
            if (string.IsNullOrWhiteSpace(ext))
                return defaultType;

            if (ext.Equals(".bmp", StringComparison.InvariantCultureIgnoreCase))
                return "image/bmp";
            if (ext.Equals(".gif", StringComparison.InvariantCultureIgnoreCase))
                return "image/gif";
            if (ext.Equals(".vnd.microsoft.icon", StringComparison.InvariantCultureIgnoreCase))
                return "image/vnd.microsoft.icon";
            if (ext.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                return "image/jpeg";
            if (ext.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
                return "image/jpeg";
            if (ext.Equals(".png", StringComparison.InvariantCultureIgnoreCase))
                return "image/png";
            if (ext.Equals(".tiff", StringComparison.InvariantCultureIgnoreCase))
                return "image/tiff";
            if (ext.Equals(".wmf", StringComparison.InvariantCultureIgnoreCase))
                return "image/wmf";

            return defaultType;
        }
    }
}